#include <iostream>
#include <vector>
#include <algorithm>
#include <cassert>

using namespace std;
// 15.三数之和
// 给你一个整数数组 nums ，判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i != j、i != k 且 j != k ，同时还满足 nums[i] + nums[j] + nums[k] == 0 。
// 请你返回所有和为 0 且不重复的三元组。
class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        assert(nums.size() >= 3);

        vector<vector<int>> res;
        sort(nums.begin(),nums.end());
        int n = nums.size();
        for(int i = 0; i < n-2; i++) {
            while (nums[i] == nums[i-1] && i < n-2 && i > 0) {  // 往前对比
                i++;
            }
//            if(i >= n-2) break;
            int target = -nums[i];
            for(int l = i+1, r = n - 1; l < r; l++) {
                while (nums[l] + nums[r] > target && l < r)
                    r--;
                if(l >= r) break;
                if(nums[l] + nums[r] == target) {
                    vector<int> ans = {nums[i],nums[l],nums[r]};
                    res.push_back(ans);
                }
            }
        }
        return res;
    }
};

int main() {
//    vector<int> nums1 = {-1, 0, 1, 2, -1, -4};
//    vector<vector<int>> res1 = Solution().threeSum(nums1);
//    for( int i = 0 ; i < res1.size() ; i ++ ){
//        for( int j = 0 ; j < res1[i].size() ; j ++ )
//            cout<<res1[i][j]<<" ";
//        cout<<endl;
//    }
    cout << endl;
    vector<int> nums2 = {0,0,0,0};
    vector<vector<int>> res2 = Solution().threeSum(nums2);
    for( int i = 0 ; i < res2.size() ; i ++ ){
        for( int j = 0 ; j < res2[i].size() ; j ++ )
            cout<<res2[i][j]<<" ";
        cout<<endl;
    }
    return 0;
}
